import React, { PureComponent } from 'react'
import Button from '../button/Button'
import { intl } from '../../intl/intl'

import './pagination.less'

class Pagination extends PureComponent {
  static defaultProps = {
    theme: 'night',
    className: '',
    style: {},
    currentPage: 1,
    totalPage: 1,
    onPageChange: () => {}
  }

  state = {
    inputValue: ''
  }

  inputChange = (e) => {
    const { totalPage } = this.props
    const value = e.target.value
    if (/(^[1-9]\d*$)/.test(value) || (+value) <= totalPage) {
      this.setState({
        inputValue: value
      })
    }
  }

  onConfirmClick = () => {
    const { inputValue } = this.state
    if (inputValue) {
      this.props.onPageChange(+inputValue)
      this.setState({
        inputValue: ''
      })
    }
  }

  onPrePageClick = () => {
    const { currentPage, onPageChange } = this.props
    onPageChange(currentPage - 1)
  }

  onNextPageClick = () => {
    const { currentPage, onPageChange } = this.props
    onPageChange(currentPage + 1)
  }

  render () {
    const { className, style, theme, currentPage, totalPage } = this.props
    const { inputValue } = this.state
    return (
      <div className={`pagination-${theme} ${className}`} style={style}>
        <span>{currentPage}/{totalPage}</span>
        <Button
          disabled={currentPage === 1}
          datatype="pre"
          className="pagination-button"
          onClick={this.onPrePageClick}>
          <i className="pagination-button-arrow"/>
        </Button>
        <Button
          disabled={currentPage === totalPage}
          datatype="next"
          className="pagination-button"
          onClick={this.onNextPageClick}>
          <i className="pagination-button-arrow"/>
        </Button>
        <span>{intl('only')}</span>
        <input
          className="pagination-input"
          value={inputValue}
          onChange={this.inputChange}/>
        <span>{intl('page')}</span>
        <Button
          disabled={!inputValue}
          className="pagination-confirm-button"
          onClick={this.onConfirmClick}>
          {intl('confirm')}
        </Button>
      </div>
    )
  }
}

export default Pagination
